package com.example.coupon.advice;

import com.example.coupon.annotation.IgnoreResponseAdvice;
import com.example.coupon.vo.CommonResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 统一响应拦截
 * @author wangbo
 * @description:
 * @date 2021/2/110:46
 */
@RestControllerAdvice
public class CommonResponseDataAdvice implements ResponseBodyAdvice {

    /**
     * 判断是否需要对响应进行处理
     * @param methodParameter
     * @param aClass
     * @return
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        //如果当前方法所在的类标识了 IgnoreResponseAdvice 则不需要处理
        if (methodParameter.getDeclaringClass().isAnnotationPresent(IgnoreResponseAdvice.class)){
            return false;
        }
        //如果当前方法标识了 IgnoreResponseAdvice 则不需要处理
        if (methodParameter.getMethod().isAnnotationPresent(IgnoreResponseAdvice.class)){
            return false;
        }
        return true;
    }


    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {

        CommonResponse<Object> response = new CommonResponse<>(
                0,""
        );
        //如果o是null，response不需要设置data
        if (null == o) {
            return response;
            //如果o已经是CommonResponse，不需要再次处理
        }else if (o instanceof CommonResponse){
            response = (CommonResponse<Object>) o;
            // 否则 把响应对象作为CommonResponse的data部分
        }else{
            response.setData(o);
        }

        return response;
    }
}
